const http = require('http');
const path = require('path');
const url = require('url');
const fs = require('fs');
const { pathToFileURL } = require('url');

const PORT = 3008;
const MODULES_FOLDER = './modules';

// 设置允许跨域的响应头
const setCorsHeaders = (res) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
};

const server = http.createServer(async (req, res) => {
  const parsedUrl = url.parse(req.url, true);
  const pathname = parsedUrl.pathname;
  
  // 设置CORS头
  setCorsHeaders(res);
  
  // 处理预检请求(OPTIONS)
  if (req.method === 'OPTIONS') {
    res.writeHead(204);
    return res.end();
  }

  // 处理 favicon.ico 请求
  if (pathname === '/favicon.ico') {
    res.writeHead(204);
    return res.end();
  }

  if (req.method !== 'GET') {
    res.writeHead(405, { 'Content-Type': 'application/json' });
    return res.end(JSON.stringify({ error: 'Method not allowed' }));
  }

  let filename = pathname.slice(1);
  
  // 检查路径是否以 /ywgtest/ 开头
  if (filename.startsWith('ywgtest/')) {
    filename = filename.slice('ywgtest/'.length);
  }

  // 允许 .js 和 .mjs 文件
  if (!filename || (!filename.endsWith('.js') && !filename.endsWith('.mjs')) || filename.includes('..')) {
    res.writeHead(400, { 'Content-Type': 'application/json' });
    return res.end(JSON.stringify({ error: 'Invalid file name' }));
  }

  const filePath = path.join(MODULES_FOLDER, filename);

  try {
    await fs.promises.access(filePath, fs.constants.F_OK);
    const modulePath = pathToFileURL(filePath).href;
    const module = await import(modulePath);

    if (!module.default) {
      throw new Error('Module does not have a default export');
    }

    res.writeHead(200, { 
      'Content-Type': 'application/json',
      'Cache-Control': 'no-cache',
      // 这里不需要再设置CORS头，因为已经在setCorsHeaders中设置了
    });
    res.end(JSON.stringify(module.default));
  } catch (err) {
    console.error('Error:', err.message);
    if (err.code === 'ENOENT') {
      res.writeHead(404, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ error: 'File not found' }));
    } else {
      res.writeHead(500, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ 
        error: 'Error processing module',
        details: err.message 
      }));
    }
  }
});

server.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}/`);
  console.log(`Put your modules in the "${MODULES_FOLDER}" folder`);
  console.log(`Access them via http://localhost:${PORT}/121.mjs`);
  console.log('CORS is enabled - requests from any origin are allowed');
});

if (!fs.existsSync(MODULES_FOLDER)) {
  fs.mkdirSync(MODULES_FOLDER);
  console.log(`Created ${MODULES_FOLDER} directory`);
}